local class = reload("class")
local tcpS = require("tcpGateS")
local super = reload("super.basic")

---@class tcpLGateS : super.basic @tcp网关服务端
local this = class(super)

---构造函数
function this:ctor(name, ip, port)
    super.ctor(self)
    self._name = name
    self._ip = ip
    self._port = port
    self._cid = 0
end

---设置回调函数
function this:hand()
    return function (hand)
        self._hand = hand
    end
end

---启动监听
---@param gate boolean @是否是网关
function this:launch(gate)
    self._id = tcpS.bind(self._name, self._ip, self._port, gate or false, self)
    return self:hand()
end

---连接消息
function this:accept(ufd)
    local hand = self._hand
    hand.accept(ufd)
end

function this:forward_add(map)
    tcpS.forward_add(self._name, map)
end

function this:forward_del(map)
    tcpS.forward_del(self._name, map)
end

function this:forward_cls()
    tcpS.forward_cls(self._name)
end

function this:disc(ufd)
    local hand = self._hand
    hand.disc(ufd)
end

---接收消息
---@param ugfd number @网关ufd
---@param ucfd number @用户ufd
function this:recv(ugfd, ucfd, mid, pack, cid)
    local hand = self._hand
    hand.recv(ugfd, ucfd, mid, pack, cid)
end

---发送消息
function this:send(ugfd, ucfd, mid, pack)
    local cid = self._cid + 1
    self._cid = cid
    tcpS.send(self._name, ugfd, ucfd, mid, pack, cid)
    return cid
end

---回复消息
function this:reply(ugfd, ucfd, mid, pack, cid)
    tcpS.send(self._name, ugfd, ucfd, mid, pack, cid)
    return cid
end

return this
